package com.example.Less.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Component
public class ThumbnailUtil {
    
    /**
     * 生成缩略图
     * @param file 原文件
     * @param maxWidth 最大宽度
     * @param maxHeight 最大高度
     * @param quality 压缩质量 (0.0 - 1.0)
     * @return 缩略图字节数组
     */
    public byte[] generateThumbnail(MultipartFile file, int maxWidth, int maxHeight, float quality) throws IOException {
        // 检查是否为图片文件
        if (!isImageFile(file)) {
            throw new IllegalArgumentException("不支持的文件类型，仅支持图片文件生成缩略图");
        }
        
        try (InputStream inputStream = file.getInputStream()) {
            BufferedImage originalImage = ImageIO.read(inputStream);
            
            if (originalImage == null) {
                throw new IOException("无法读取图片文件");
            }
            
            // 计算缩略图尺寸
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();
            
            int thumbnailWidth, thumbnailHeight;
            
            if (originalWidth > originalHeight) {
                // 横图
                thumbnailWidth = Math.min(originalWidth, maxWidth);
                thumbnailHeight = (int) ((double) originalHeight / originalWidth * thumbnailWidth);
            } else {
                // 竖图或方图
                thumbnailHeight = Math.min(originalHeight, maxHeight);
                thumbnailWidth = (int) ((double) originalWidth / originalHeight * thumbnailHeight);
            }
            
            // 确保尺寸有效
            thumbnailWidth = Math.max(thumbnailWidth, 1);
            thumbnailHeight = Math.max(thumbnailHeight, 1);
            
            // 创建缩略图
            BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = thumbnail.createGraphics();
            
            // 设置渲染质量
            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
            // 绘制缩略图
            graphics.drawImage(originalImage, 0, 0, thumbnailWidth, thumbnailHeight, null);
            graphics.dispose();
            
            // 转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String formatName = getImageFormat(file.getOriginalFilename());
            
            // 使用ImageWriter进行质量压缩（仅对JPEG有效）
            if ("jpeg".equalsIgnoreCase(formatName) || "jpg".equalsIgnoreCase(formatName)) {
                javax.imageio.ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
                javax.imageio.ImageWriteParam param = writer.getDefaultWriteParam();
                
                if (param.canWriteCompressed()) {
                    param.setCompressionMode(javax.imageio.ImageWriteParam.MODE_EXPLICIT);
                    param.setCompressionQuality(quality);
                }
                
                javax.imageio.stream.ImageOutputStream ios = javax.imageio.ImageIO.createImageOutputStream(baos);
                writer.setOutput(ios);
                writer.write(null, new javax.imageio.IIOImage(thumbnail, null, null), param);
                writer.dispose();
                ios.close();
            } else {
                ImageIO.write(thumbnail, formatName, baos);
            }
            
            return baos.toByteArray();
        }
    }
    
    /**
     * 检查是否为图片文件
     */
    public boolean isImageFile(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null && contentType.startsWith("image/");
    }
    
    /**
     * 获取图片格式
     */
    private String getImageFormat(String filename) {
        if (filename == null) return "jpg";
        
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        return switch (extension) {
            case "png" -> "png";
            case "gif" -> "gif";
            case "bmp" -> "bmp";
            default -> "jpg";
        };
    }
    
    /**
     * 生成缩略图文件名
     */
    public String generateThumbnailFilename(String originalFilename) {
        if (originalFilename == null) return "thumbnail.jpg";
        
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex > 0) {
            return originalFilename.substring(0, dotIndex) + "_thumb" + originalFilename.substring(dotIndex);
        } else {
            return originalFilename + "_thumb.jpg";
        }
    }
}